/**
 * 退款服务实现类 - 处理支付退款申请的核心业务逻辑
 *
 * 开发人员：徐少洋
 * 开发时间：2025-10-25 至 2025-10-28
 * 模块职责：实现退款申请的创建、验证、状态管理等核心业务逻辑，与支付订单关联处理
 *
 * 技术要点：
 * - 退款申请的创建和管理机制
 * - 支付订单关联和金额验证
 * - 多租户退款数据隔离处理
 * - 退款状态管理和业务规则验证
 * - 异常处理和事务管理机制
 *
 * 开发故事：负责退款服务的核心业务逻辑实现，与退款控制器和支付系统深度集成，确保退款申请流程的完整性和安全性。
 */
package com.pbl.service.impl;

import com.pbl.common.enums.RefundStatus;
import com.pbl.common.exception.BizException;
import com.pbl.entity.PaymentOrder;
import com.pbl.entity.RefundRecord;
import com.pbl.repository.PaymentOrderRepository;
import com.pbl.repository.RefundRecordRepository;
import com.pbl.service.RefundService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class RefundServiceImpl implements RefundService {

    private final RefundRecordRepository refundRecordRepository;
    private final PaymentOrderRepository paymentOrderRepository;

    /**
     * 构造退款服务实现
     * @param refundRecordRepository 退款记录数据访问层
     * @param paymentOrderRepository 支付订单数据访问层
     */
    public RefundServiceImpl(RefundRecordRepository refundRecordRepository, PaymentOrderRepository paymentOrderRepository) {
        this.refundRecordRepository = refundRecordRepository;
        this.paymentOrderRepository = paymentOrderRepository;
    }

    @Override
    public RefundRecord requestRefund(Long paymentOrderId, BigDecimal amount) {
        PaymentOrder po = paymentOrderRepository.findById(paymentOrderId)
                .orElseThrow(() -> new BizException(404, "支付订单不存在"));
        RefundRecord rr = new RefundRecord();
        rr.setEnterprise(po.getEnterprise());
        rr.setPaymentOrder(po);
        rr.setOutTradeNo(po.getOutTradeNo());
        rr.setTradeNo(po.getTradeNo());
        rr.setRefundAmount(amount);
        rr.setStatus(RefundStatus.CREATED);
        return refundRecordRepository.save(rr);
    }
}
